import base64
import hashlib

import requests
from bs4 import BeautifulSoup
import time


def parse_items():
    bookname = "逃避自由"
    url = rf"https://z-library.sk/s/{bookname}"
    print(f"url: {url}")
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    book_item = soup.find_all("div", class_="book-item resItemBoxBooks")
    items = {}
    for item in book_item:
        num = item.find("div", class_="counter").get_text().strip()
        book_name = item.find("div", slot="title").get_text()
        img = item.find("img").get('data-src')
        author = item.find("div", slot="author").get_text()
        page_href = f"https://z-library.sk{item.find("z-bookcard").get("href")}"
        download_href = f"https://z-library.sk{item.find("z-bookcard").get("download")}"
        size = item.find("z-bookcard").get("filesize")
        items[num] = {
            "book_name": book_name,
            "img": img,
            "author": author,
            "page_href": page_href,
            "download_href": download_href,
            "size": size
        }
    return items


def parse_page(html):
    soup = BeautifulSoup(html, "html.parser")
    book_title = soup.find("h1", class_="book-title").get_text().strip()
    book_author = soup.find("a", title="Find all the author's book").get_text().strip()
    return f"{book_title}({book_author})(Z-Library)"


def md5hex_base64url(text: str) -> str:
    # 1. 得到 MD5 的 hex 串
    md5_hex = hashlib.md5(text.encode("utf-8")).hexdigest()  # 32 字符串

    # 2. 对 hex 串做 Base64URL 编码
    b64url = base64.urlsafe_b64encode(md5_hex.encode("utf-8")).decode("utf-8")

    # 3. 去掉 '=' 填充
    return b64url.rstrip("=")


result = {}
times = 1
while not result:
    result = parse_items()
    print(f"第{times}次：{result}")
    times += 1
    time.sleep(1)

response = requests.get(result['2']['page_href'])
# print(response.text)
name = parse_page(response.text)
print(name)
print(md5hex_base64url(name))
